package com.wkk.utils;


import cn.hutool.core.bean.BeanUtil;
import com.wkk.config.MyX509TrustManager;
import lombok.extern.slf4j.Slf4j;

import javax.net.ssl.HttpsURLConnection;
import javax.net.ssl.SSLContext;
import javax.net.ssl.SSLSocketFactory;
import javax.net.ssl.TrustManager;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;

import java.net.URL;

/**
 * @author : WangKeKe
 * @date : 2020/8/15 22:55
 * Description : 下载在线资源工具类
 */

@Slf4j
public class DownLoadByUrlUtil {


    public static void main(String[] args) throws Exception {
        downLoad("https://webfs.yun.kugou.com/202011301107/eab8bd59ee19f1d517327815ea434014/G241/M09/17/11/0ZQEAF-ZHSqAQgM1ADN50PCHkVI718.mp3",
                "2020-11-30-蓝蓝的夜",
                "mp3",
                "D:/aboutMusic/");
    }

    /**
     * 下载在线资源
     *
     * @param urlInfo      资源路径—— https://www.badiu.com/zhongguo.jpg
     * @param fileName     下载后文件名——示例 万里长城永不倒
     * @param fileType     下载文件类型后缀——示例 mp3 mp4 avi txt jpg
     * @param filePosition 下载文件路径——示例 D:/myMusic/ 为空则下载到本项目目录下
     * @throws Exception 下载异常
     */
    private static void downLoad(String urlInfo, String fileName, String fileType, String filePosition) throws Exception {
        // 创建SSLContext对象，并使用我们指定的信任管理器初始化
        TrustManager[] tm = {new MyX509TrustManager()};
        SSLContext sslContext = SSLContext.getInstance("SSL", "SunJSSE");
        sslContext.init(null, tm, new java.security.SecureRandom());
        // 从上述SSLContext对象中得到SSLSocketFactory对象
        SSLSocketFactory ssf = sslContext.getSocketFactory();
        URL url = new URL(urlInfo);
        HttpsURLConnection urlConnection = (HttpsURLConnection) url.openConnection();
        urlConnection.setSSLSocketFactory(ssf);
        // 设置连接的信息：允许传入传出，不设置缓存
        urlConnection.setDoInput(true);
        urlConnection.setDoOutput(true);
        InputStream is = urlConnection.getInputStream();
        FileOutputStream fos = new FileOutputStream(new File(filePosition + fileName + "." + fileType));
        byte[] buffer = new byte[1024];
        int len;
        while ((len = is.read(buffer)) != -1) {
            fos.write(buffer, 0, len);
        }
        fos.flush();
        fos.close();
        is.close();
        urlConnection.disconnect();
        log.info("文件：" + fileName + "." + fileType + ">>>>已经成功下载到：" + filePosition);
    }

}
